package cn.yitun.chat.yitunserverfilecore.controller;

import cn.yitun.chat.yituncommonmessage.result.ResultMessage;
import cn.yitun.chat.yituncommonutil.YitunStringUtil;
import cn.yitun.chat.yitunservercommonlib.basebean.web.JwtUserDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.po.common.FileDataInfo;
import cn.yitun.chat.yitunserverfilecore.component.DownloadFileHandler;
import cn.yitun.chat.yitunserverfilecore.service.FileServerConfigService;
import cn.yitun.chat.yitunserverfilecore.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author yitun
 * @date 2017-11-25 09:28:59
 *
 */
@Controller
@RequestMapping("/file/image")
public class FileUploadController {

	@Autowired
	FileService fileService;
	@Resource
	FileServerConfigService fileServerConfigService;
	DownloadFileHandler dfh = new DownloadFileHandler();
	
	@CrossOrigin
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST,value = "/uploads")
	public Object uploads(@RequestParam("file") MultipartFile[] files, HttpServletRequest request, HttpServletResponse response) {
		ResultMessage rm = new ResultMessage();
		if (null != files) {
		}
		return rm;
	}

	@CrossOrigin
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST,value ="/upload")
	public Object upload(HttpServletRequest request, JwtUserDto jwtUserDto) {
		ResultMessage rm = new ResultMessage();
		Long userId = jwtUserDto.getUserId();
//		Long userId = YitunStringUtil.isNotEmpty(request.getParameter("userId"))
//				? null : Long.parseLong(request.getParameter("userId")) ;
		List<FileDataInfo> list = fileService.uploadByIO(request, userId);

		Map<String, Object> dataMap = new HashMap<>();

		if (null != list && !list.isEmpty()) {
			FileDataInfo data = list.get(0);

			String name = data.getName();
			String saveName = data.getSaveName();
			String nodePath = data.getNodePath();
			List<Map<String, Object>> items = new ArrayList<>();
			dataMap.put("id", data.getId());
			dataMap.put("name", name);
			dataMap.put("size", data.getSize());
			dataMap.put("url", fileServerConfigService.getFileUrl(nodePath + saveName));
			items.add(dataMap);
		}
		rm.bodyPut("data", dataMap);
		return rm;
	}

	@RequestMapping("/download")
	public void download(Long id, HttpServletRequest request, HttpServletResponse response) {
		if (id != null ) {
			FileDataInfo fileData = fileService.getFileData(id);
			if (null != fileData) {
				dfh.downloadByIO(request, response, fileData);
			}
		}
	}
}
